<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 在排序数组中查找元素的第一个数和最后一个数
        // (left, right) 左开右开
        const lowerBound = function (nums, target) {
            let left = -1;
            // 要写成right = nums.length，不是nums.length - 1，因为最后的right是没有意义的，可以取
            let right = nums.length;
            let mid;
            // 要写成left < right，因为[left, right)是没有意义的
            while (left + 1 < right) {
                mid = left + ((right - left) >> 1)
                if (nums[mid] >= target) {
                    // 要写成right = mid，而不是mid+1
                    right = mid
                } else {
                    left = mid
                }
            }
            // return right
            return right
        }
        const searchRanage = function(nums, target) {
            const start = lowerBound(nums, target)
            console.log(start, 'start');
            if (start === nums.length || nums[start] !== target) {
                return [-1, -1]
            }
            const end = lowerBound(nums, target + 1) - 1
            return [start, end]
        };
        console.log(searchRanage([5, 7, 7, 8, 9, 10], 9));
        // console.log(searchRanage([5, 7, 7, 8, 8, 8, 9, 9, 7, 9, 10], 9));
    </script>
</body>

</html>